package com.xiaoshu.druid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
@EnableConfigurationProperties
@ConditionalOnResource(resources={"classpath:druid.properties"})
@AutoConfigureAfter(DruidProperties.class)
public class DruidConfiguration {
	
	@Autowired
	private DruidProperties properties;

	@Bean
	public DruidDataSource getDruidDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(properties.getUrl());
		dataSource.setPassword(properties.getPassword());
		dataSource.setUsername(properties.getUsername());
		dataSource.setDriverClassName(properties.getDriverClassName());
		/*
		 * 配置初始化大小、最小、最
		 */
		dataSource.setInitialSize(5);
		dataSource.setMinIdle(5);
		dataSource.setMaxActive(20);
		/*
		 * 配置获取连接等待超时的时间
		 */
		dataSource.setMaxWait(60000);
		/*
		 * 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
		 */
		dataSource.setTimeBetweenEvictionRunsMillis(60000);
		/*
		 * 配置一个连接在池中最小生存的时间，单位是毫秒
		 */
		dataSource.setMinEvictableIdleTimeMillis(300000);

		dataSource.setValidationQuery("SELECT 'X'");
		dataSource.setTestWhileIdle(true);
		dataSource.setTestOnBorrow(false);
		dataSource.setTestOnReturn(false);
		/*
		 * 打开PSCache，并且指定每个连接上PSCache的大小
		 */
		dataSource.setPoolPreparedStatements(false);
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(25);
		return dataSource;
	}

	@Bean
	public ServletRegistrationBean druidServlet() {
		return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
	}

	@Bean
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}
}
